package com.chukun.netty.grpc;

import com.chukun.netty.proto.*;
import io.grpc.stub.StreamObserver;

import java.time.LocalDateTime;

/**
 * @author chukun
 */
public class GrpcStudentService extends StudentServiceGrpc.StudentServiceImplBase {

    @Override
    public void getRealNameByUserName(StudentRequest request, StreamObserver<StudentResponse> responseObserver) {
        System.out.println("received from client : "+request.getUsername());

        responseObserver.onNext(StudentResponse.newBuilder().setRealname("tom").build());
        responseObserver.onCompleted();
    }

    @Override
    public void getStudentsByAge(StudentAge request, StreamObserver<StudentResponse> responseObserver) {
        responseObserver.onNext(StudentResponse.newBuilder().setRealname("111").build());
        responseObserver.onNext(StudentResponse.newBuilder().setRealname("222").build());
        responseObserver.onNext(StudentResponse.newBuilder().setRealname("333").build());
        responseObserver.onCompleted();
    }

    @Override
    public StreamObserver<StudentAge> getStudentWrapperByAges(StreamObserver<StudentResponseList> responseObserver) {
        return new StreamObserver<StudentAge>() {
            @Override
            public void onNext(StudentAge studentAge) {
                System.out.println("getStudentWrapperByAges received data : "+studentAge.getAge());
            }

            @Override
            public void onError(Throwable throwable) {
                System.out.println(throwable.getMessage());
            }

            @Override
            public void onCompleted() {
                StudentInfo student0 = StudentInfo.newBuilder().setAge(23).setCity("北京").build();
                StudentInfo student1 = StudentInfo.newBuilder().setAge(22).setCity("西安").build();
                StudentResponseList studentResponseList = StudentResponseList.newBuilder().addStudents(student0).addStudents(student1).build();
                responseObserver.onNext(studentResponseList);
                responseObserver.onCompleted();
            }
        };
    }

    @Override
    public StreamObserver<StreamRequestInfo> getStudentWrapperResponseWrapper(StreamObserver<StreamResponseInfo> responseObserver) {
        return new StreamObserver<StreamRequestInfo>() {
            @Override
            public void onNext(StreamRequestInfo streamRequestInfo) {
                System.out.println("getStudentWrapperResponseWrapper received data : "+streamRequestInfo.getRequestInfo());
                responseObserver.onNext(StreamResponseInfo.newBuilder().setResponseInfo(LocalDateTime.now().toString()).build());
            }

            @Override
            public void onError(Throwable throwable) {
                System.out.println(throwable.getMessage());
            }

            @Override
            public void onCompleted() {
                responseObserver.onCompleted();
            }
        };
    }
}
